/**
 * Project Name:九色鹿
 * File Name:UserDetailsServiceImpl.java
 * Package Name:com.fxp.project.jiuselu.web.security.service.impl
 * Date:2021-08-29 5:30 下午
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.exceptions.ParamException;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.mapper.JslUserMapper;
import com.fxp.project.jiuselu.web.security.userdetails.CustomerUserDetails;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * ClassName: UserDetailsServiceImpl<br/>
 * Function: 权限配置的用户业务类实现<br/>
 * Date: 2021-08-29 5:30 下午<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK 1.8
 */
@Log4j2
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    JslUserMapper jslUserMapper;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] split = username.split(",");

        QueryWrapper<JslUser> queryWrapper = new QueryWrapper<>();
        if (split.length==1){
            queryWrapper.eq("user_phone", split[0]).or().eq("user_id", split[0]).eq("enable",1);
        }else {
            queryWrapper.eq("user_phone", split[0]).eq("level",split[1]).or().eq("user_id", split[0]).eq("enable",1);
        }



        JslUser jslUser = jslUserMapper.selectOne(queryWrapper);

        if (jslUser==null){
            throw new ParamException(500,"用户未注册或已被冻结");
        }

        CustomerUserDetails customerUserDetails = new CustomerUserDetails();
        customerUserDetails.setJslUser(jslUser);
        return customerUserDetails;
    }
}

